package com.wzt.lianfirecontrol.activity;


import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.devicexuncha.XunChaDeviceListModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * 设备巡查nfc
 */
public class NfcDeviceActivity extends BaseActivity {

    private Bundle bundle;

    private NfcAdapter nfcAdapter;
    private PendingIntent pi;

    private View include_head_title;
    private ImageView iv_back;
    public TextView tv_title;

    private TextView tv_device_id;
    private TextView tv_device_name;
    private TextView tv_device_system;
    private TextView tv_device_type;
    private TextView tv_device_building;
    private TextView tv_device_floor;
    private TextView tv_device_location;

    private Button bt_submit_problem;
    private Button bt_submit_complete;

    private View include_progress_bar;
    private View include_no_data;
    private View include_no_net;

    private String currentCardId;
    private static final int GET_DEVICE_DATA_WHAT = 0;
    private static final int COMPLETE_ALL_WHAT = 1;

    private Dialog completeDialog;
    private Dialog openNfcDialog;
    private static final int OPEN_NFC_WHAT = 1;

    private boolean isFirstLoad = true;
    private boolean isLoading = false;

    private String recordId;
    private String planId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!UserInfoModel.isLogin(this)){
            ToastUtils.showToast(this, "未登录");
            finish();
        }
        setContentView(R.layout.a_nfc_deal_data);
        setImmerseLayout(findViewById(R.id.include_head_title), findViewById(R.id.rl_head_content));
        PreferencesUtils.putString(this, ConstData.NEEDNFCDIALOGSHOW, "1");
        Intent intent = getIntent();
        bundle = intent.getExtras();
        if (null != bundle && bundle.containsKey(ConstData.ACTIONPARAMS)){
            HashMap<String, String> hashMap = (HashMap<String, String>) bundle.getSerializable(ConstData.ACTIONPARAMS);
            if (hashMap.containsKey("planId")){
                planId = hashMap.get("planId");
            }
        }
        if (StringUtils.isEmpty(planId)){
           // ToastUtils.showToast(this, "planId为空");
            finish();
            return;
        }
        pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        initView();
        checkNfcStatus();

        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            processIntent(intent);
        }
    }

    private void initView() {
        iniHeadTitle();

        initDeviceView();

        include_progress_bar = findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(this, include_progress_bar);

        include_no_data = findViewById(R.id.include_no_data);

        include_no_net = findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDeviceData();
            }
        });
    }

    private void iniHeadTitle() {
        include_head_title = findViewById(R.id.include_head_title);
        include_head_title.setBackground(getResources().getDrawable(R.drawable.shape_head_title_bg_frame));
        iv_back = findViewById(R.id.iv_back);
        iv_back.setImageResource(R.drawable.back_white);
        iv_back.setVisibility(View.VISIBLE);
        tv_title = findViewById(R.id.tv_title);
        tv_title.setTextColor(getResources().getColor(R.color.white));
        tv_title.setText("NFC智能巡检");
        findViewById(R.id.v_divdier_line).setVisibility(View.GONE);
    }

    private void initDeviceView() {
        tv_device_id = findViewById(R.id.tv_device_id);
        tv_device_name = findViewById(R.id.tv_device_name);
        tv_device_system = findViewById(R.id.tv_device_system);
        tv_device_type = findViewById(R.id.tv_device_type);
        tv_device_building = findViewById(R.id.tv_device_building);
        tv_device_floor = findViewById(R.id.tv_device_floor);
        tv_device_location = findViewById(R.id.tv_device_location);

        bt_submit_problem = findViewById(R.id.bt_submit_problem);
        bt_submit_problem.setVisibility(View.GONE);
        bt_submit_complete = findViewById(R.id.bt_submit_complete);
        bt_submit_complete.setVisibility(View.GONE);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            processIntent(intent);
        }
    }

    /**
     * Parses the NDEF Message from the intent and prints to the TextView
     */
    private void processIntent(Intent intent) {
        //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String cardId = Utils.ByteArrayToHexString(tagFromIntent.getId());
        if (StringUtils.isEmpty(cardId)){
            return;
        }
        if (null != completeDialog && completeDialog.isShowing()){
            return;
        }
        if (StringUtils.isEmpty(currentCardId)){
            currentCardId = cardId;
            getDeviceData();
        }else if (!currentCardId.equals(cardId)){
            completeDialog = DialogUtils.createNfcDeviceCompleteDialog(this, "切换巡查设备",
                    "取消", "确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            completeDialog.dismiss();
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            completeDialog.dismiss();
                            clearData();
                            currentCardId = cardId;
                            getDeviceData();
                        }
                    });
            completeDialog.show();
        }

    }

    private void getDeviceData(){
        if (StringUtils.isEmpty(currentCardId)){
            ToastUtils.showToast(this, "未检测到设备");
            return;
        }
        if (null == tv_title){
            initView();
        }
        if (Utils.hasNetwork(this)){
            include_progress_bar.setVisibility(View.VISIBLE);
            include_no_net.setVisibility(View.GONE);
            initNfcHttpHelper();
        }else {
            include_progress_bar.setVisibility(View.GONE);
            include_no_net.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 查询设备信息
     */
    private void initNfcHttpHelper() {
        if (StringUtils.isEmpty(currentCardId)){
            return;
        }
        if (!Utils.hasNetwork(this)){
            include_no_net.setVisibility(View.VISIBLE);
            isLoading = false;
            return;
        }
        if (isLoading){
            return;
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("rfid", currentCardId);
        hashMap.put("planId", planId);

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        NfcHttpHelper nfcHttpHelper = new NfcHttpHelper(this, Url.XUNCHA_DEVICE_FIND_BY_NFC_URL,
                GET_DEVICE_DATA_WHAT, handler, true, url_params);
        nfcHttpHelper.setParseJsonData(new NfcParseJsonData());
        nfcHttpHelper.getHttpRequest(true);
        isLoading = true;
    }

    /**
     * 设备巡查完成请求
     */
    private void initCompleteHttpHelper(){
        if (StringUtils.isEmpty(recordId)){
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", recordId);

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        NfcHttpHelper nfcHttpHelper = new NfcHttpHelper(this, Url.XUNCHA_DEVICE_COMPLETE_URL,
                COMPLETE_ALL_WHAT, handler, true, url_params);
        nfcHttpHelper.setParseJsonData(new NfcParseJsonData());
        nfcHttpHelper.getHttpRequest(true);
    }

    private class NfcHttpHelper extends HttpHelper {
        public NfcHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    private class NfcParseJsonData extends ParseJsonData {

        public NfcParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try {
                switch (what) {
                    case GET_DEVICE_DATA_WHAT:
                        XunChaDeviceListModel xunChaDeviceListModel = JSONUtil.jsonObjectToBean(
                                new JSONObject(dataStr), XunChaDeviceListModel.class);
                        bundle.putSerializable("model", xunChaDeviceListModel);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case COMPLETE_ALL_WHAT:

                        break;
                }
            }catch (Exception e){}
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            if (msg.what == COMPLETE_ALL_WHAT && ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
                // 设备完成
                include_progress_bar.setVisibility(View.GONE);
                // 需要弹窗
                completeDialog = DialogUtils.createNfcDeviceCompleteDialog(this, "当前设备巡查完成",
                        "返回列表", "继续巡查", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                completeDialog.dismiss();
                                NfcDeviceActivity.this.finish();
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                completeDialog.dismiss();
                                clearData();
                            }
                        });
                completeDialog.show();
                return;
            }
            if (msg.what == GET_DEVICE_DATA_WHAT){
                isLoading = false;
                currentCardId = "";
                include_progress_bar.setVisibility(View.GONE);
                ToastUtils.showToast(this, "未查询到该设备");
                clearData();
                return;
            }
            return;
        }
        switch (msg.what){
            case GET_DEVICE_DATA_WHAT:
                isLoading = false;
                include_progress_bar.setVisibility(View.GONE);
                setDeviceData((XunChaDeviceListModel) bundle.getSerializable("model"));
                break;
        }
    }

    /**
     * 处理设备数据
     * @param deviceListModel
     */
    private void setDeviceData(XunChaDeviceListModel deviceListModel){
        if (null != deviceListModel){
            recordId = deviceListModel.getId();
            tv_device_id.setText(deviceListModel.getEquId());
            tv_device_name.setText(deviceListModel.getEquName());
            tv_device_system.setText(deviceListModel.getEquSysName());
            tv_device_type.setText(deviceListModel.getEquTypeName());
            tv_device_building.setText(deviceListModel.getBuildingName());
            tv_device_floor.setText(deviceListModel.getFloorName());
            tv_device_location.setText(deviceListModel.getAddress());
            // 判断设备状态
            if ("1".equals(deviceListModel.getStatus())){
                // 待检查
                bt_submit_problem.setVisibility(View.VISIBLE);
                bt_submit_problem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PreferencesUtils.putString(NfcDeviceActivity.this, ConstData.NEEDNFCDIALOGSHOW, "1");
                        HashMap<String, String> url_params = new HashMap<>();
                        Bundle bundle = new Bundle();
                        bundle.putString("recordId", recordId);
                        bundle.putSerializable("deviceListModel", deviceListModel);
                        NfcDeviceActivity.this.setClickAction(ConstData.SHOWFRAG, ConstData.ADDXUNCHADETAILQES, "问题详情", url_params, bundle);
                    }
                });
                bt_submit_complete.setVisibility(View.VISIBLE);
                bt_submit_complete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initCompleteHttpHelper();
                    }
                });
            }else {
                // 已完成
                bt_submit_problem.setVisibility(View.GONE);
                bt_submit_complete.setVisibility(View.GONE);
                completeDialog = DialogUtils.createNfcDeviceCompleteDialog(this, "当前设备巡查完成",
                        "返回列表", "继续巡查", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        completeDialog.dismiss();
                        NfcDeviceActivity.this.finish();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        completeDialog.dismiss();
                        //clearData();
                    }
                });
                completeDialog.show();
            }
        }else {
            currentCardId = "";
            ToastUtils.showToast(this, "未查询到该设备");
        }
    }

    private void clearData(){
        currentCardId = "";
        recordId = "";
        tv_device_id.setText("");
        tv_device_name.setText("");
        tv_device_system.setText("");
        tv_device_type.setText("");
        tv_device_building.setText("");
        tv_device_floor.setText("");
        tv_device_location.setText("");
        bt_submit_problem.setVisibility(View.GONE);
        bt_submit_complete.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 提交问题后返回页面 发送完成请求
        if ("0".equals(PreferencesUtils.getString(this, ConstData.NEEDNFCDIALOGSHOW, "1"))){
            initCompleteHttpHelper();
            PreferencesUtils.putString(this, ConstData.NEEDNFCDIALOGSHOW, "1");
        }
        // 返回更新数据
        else if (!isFirstLoad){
            initNfcHttpHelper();
        }
        if (null != nfcAdapter) {
            nfcAdapter.enableForegroundDispatch(this, pi, null, null);
        }
        isFirstLoad = false;
    }

    /**
     * 判断nfc状态
     */
    private boolean checkNfcStatus(){
        // 获取默认的NFC控制器
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            ToastUtils.showToast(this, "此设备不支持nfc功能");
            finish();
            return false;
        }
        if (!nfcAdapter.isEnabled()) {
            openNfcDialog = DialogUtils.createSureAndCancelDialog(this, "此功能需打开NFC",
                    "取消", "打开", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            openNfcDialog.dismiss();
                            NfcDeviceActivity.this.finish();
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            openNfcDialog.dismiss();
                            // 打开NFC
                            Utils.openNfc(NfcDeviceActivity.this, OPEN_NFC_WHAT);
                        }
                    });
            openNfcDialog.show();
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_NFC_WHAT){
            NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
            if (nfcAdapter == null) {
                ToastUtils.showToast(this, "此设备不支持nfc功能");
                finish();
                return;
            }
            if (!nfcAdapter.isEnabled()) {
                ToastUtils.showToast(this, "nfc功能未打开");
                return;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DialogUtils.closeDialog(completeDialog);
        DialogUtils.closeDialog(openNfcDialog);
    }
}